<?php
// 数据库配置文件
define('DB_HOST', 'localhost');
define('DB_NAME', 'sqlbookmarkmanager');
define('DB_USER', 'bookmarkmanager');
define('DB_PASS', '123456');
define('DB_CHARSET', 'utf8');

// JWT密钥配置
// 共享主机环境：生成安全的随机密钥
$jwtSecret = 'bookmark_' . bin2hex(random_bytes(32)) . '_' . time();
define('JWT_SECRET', $jwtSecret);
define('JWT_ALGORITHM', 'HS256');

// 会话配置
define('SESSION_DURATION', 7 * 24 * 60 * 60); // 7天
define('REMEMBER_ME_DURATION', 30 * 24 * 60 * 60); // 30天

// 安全配置
define('PASSWORD_MIN_LENGTH', 6);
define('MAX_LOGIN_ATTEMPTS', 5);
define('LOGIN_ATTEMPT_TIMEOUT', 15 * 60); // 15分钟

// CORS配置
define('ALLOWED_ORIGINS', ['http://localhost', 'http://127.0.0.1']);

// 错误报告配置
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// 设置时区
date_default_timezone_set('Asia/Shanghai');

// 数据库连接类
class Database {
    private static $instance = null;
    private $connection;
    
    private function __construct() {
        try {
            $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . DB_CHARSET
            ];
            
            $this->connection = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (PDOException $e) {
            error_log("数据库连接失败: " . $e->getMessage());
            throw new Exception("数据库连接失败");
        }
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function getConnection() {
        return $this->connection;
    }
    
    // 防止克隆
    private function __clone() {}
    
    // 防止反序列化
    public function __wakeup() {
        throw new Exception("Cannot unserialize singleton");
    }
}

// 工具函数
function sendJsonResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function sendErrorResponse($message, $statusCode = 400) {
    sendJsonResponse(['success' => false, 'message' => $message], $statusCode);
}

function sendSuccessResponse($data = null, $message = null) {
    $response = ['success' => true];
    if ($message) $response['message'] = $message;
    if ($data) $response['data'] = $data;
    sendJsonResponse($response);
}

function validateInput($data, $rules) {
    $errors = [];
    
    foreach ($rules as $field => $rule) {
        $value = isset($data[$field]) ? trim($data[$field]) : '';
        
        // 必填验证
        if (isset($rule['required']) && $rule['required'] && empty($value)) {
            $errors[$field] = $rule['message'] ?? "{$field}是必填项";
            continue;
        }
        
        // 如果字段为空且不是必填，跳过其他验证
        if (empty($value)) continue;
        
        // 长度验证
        if (isset($rule['min_length']) && strlen($value) < $rule['min_length']) {
            $errors[$field] = $rule['message'] ?? "{$field}长度不能少于{$rule['min_length']}个字符";
        }
        
        if (isset($rule['max_length']) && strlen($value) > $rule['max_length']) {
            $errors[$field] = $rule['message'] ?? "{$field}长度不能超过{$rule['max_length']}个字符";
        }
        
        // 邮箱验证
        if (isset($rule['email']) && $rule['email'] && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
            $errors[$field] = $rule['message'] ?? "{$field}格式不正确";
        }
        
        // URL验证
        if (isset($rule['url']) && $rule['url'] && !filter_var($value, FILTER_VALIDATE_URL)) {
            $errors[$field] = $rule['message'] ?? "{$field}格式不正确";
        }
        
        // 正则验证
        if (isset($rule['pattern']) && !preg_match($rule['pattern'], $value)) {
            $errors[$field] = $rule['message'] ?? "{$field}格式不正确";
        }
    }
    
    return $errors;
}

function generateSecureToken($length = 32) {
    return bin2hex(random_bytes($length));
}

function hashPassword($password) {
    return password_hash($password, PASSWORD_ARGON2ID);
}

function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}

// CORS处理
function handleCORS() {
    $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
    
    if (in_array($origin, ALLOWED_ORIGINS) || in_array('*', ALLOWED_ORIGINS)) {
        header("Access-Control-Allow-Origin: $origin");
    }
    
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    header('Access-Control-Allow-Credentials: true');
    
    // 处理预检请求
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit;
    }
}

// 获取请求数据
function getRequestData() {
    $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
    
    if (strpos($contentType, 'application/json') !== false) {
        $input = file_get_contents('php://input');
        return json_decode($input, true) ?: [];
    }
    
    return $_REQUEST;
}

// 日志记录
function logActivity($message, $level = 'INFO') {
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[$timestamp] [$level] $message" . PHP_EOL;
    error_log($logMessage, 3, 'logs/app.log');
}

// 创建日志目录
if (!file_exists('logs')) {
    mkdir('logs', 0755, true);
}
?>
